package com.hjlsoft.aftp.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

public class MD5Util {

	public static String encrypt(String s) {
		return encrypt(s.getBytes());
	}

	public static String encrypt(byte[] source) {
		String s = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(source);
			s = toHexString(md.digest());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}

	private static String toHexString(byte[] digest) {
		char str[] = new char[16 * 2];
		int k = 0;
		for (int i = 0; i < 16; i++) {
			byte byte0 = digest[i];
			str[k++] = hexDigits[byte0 >>> 4 & 0xf];
			str[k++] = hexDigits[byte0 & 0xf];
		}
		return new String(str);
	}

	public static String getFileMD5String(File file) throws IOException {
		FileInputStream in = null;
		FileChannel ch = null;
		try {
			in = new FileInputStream(file);
			MessageDigest messagedigest = MessageDigest.getInstance("MD5");
			ch = in.getChannel();
			MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
			messagedigest.update(byteBuffer);
			return toHexString(messagedigest.digest());
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			IoUtil.close(ch);
			IoUtil.close(in);
		}
	}

	static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

}
